#include "ChatLogWidget.h"

ChatLogWidget::ChatLogWidget(QWidget *parent) :
    QTextBrowser(parent) {
    initializeStyleSheet();
    chatScrollBar = verticalScrollBar();

    firstBlock = true;
    scrolledBottom = true;
    lastChatType = Chat::NONE;
}

void ChatLogWidget::append(QString chat, Chat::ChatType type) {
    scrolledBottom = chatScrollBar->value() == chatScrollBar->maximum();
    switch (type) {
    case Chat::NONE:
        if (firstBlock) {
            firstBlock = false;
        } else {
            chatCursor->insertBlock(standardFormat);
        }
        break;
    case Chat::PLAYER_CHAT:
        if (firstBlock) {
            firstBlock = false;
            chat = "<div class=\"namechat\"><span class=\"name\">You:  </span>" + chat + "</div>";
        } else if (type != lastChatType) {
            chatCursor->insertBlock(standardFormat);
            chat = "<div class=\"namechat\"><span class=\"name\">You:  </span>" + chat + "</div>";
        } else {
            chatCursor->insertBlock(indentedFormat);
            chat = "<div class=\"chat\">" + chat + "</div>";
        }
        break;
    case Chat::OPPONENT_CHAT:
        if (type != lastChatType) {
            chatCursor->insertBlock(standardFormat);
            chat = "<div class=\"namechat\"><span class=\"name\">Opponent:  </span>" + chat + "</div>";
        } else {
            chatCursor->insertBlock(indentedFormat);
            chat = "<div class=\"chat\">" + chat + "</div>";
        }
        break;
    }
    chatCursor->insertHtml(chat);
    if (scrolledBottom) {
        chatScrollBar->setValue(chatScrollBar->maximum());
    }
    lastChatType = type;
}

void ChatLogWidget::initializeStyleSheet() {
    QString cssString = "div {text-indent: -20px; margin-left: 20px; margin-top: 3px} ";
    cssString += "div.notice {font-weight: bold; } ";
    cssString += "div.urgent {font-weight: bold; color: red; } ";
    cssString += "div.request {color: blue; } ";
    cssString += "div.accept {color: green; } ";
    cssString += "div.reject {color: red; } ";
    cssString += "div.namechat {} ";
    cssString += "div.chat {text-indent: 0px; } ";
    cssString += "span.name {font-weight: bold; white-space: pre; } ";
    chatHtml = new QTextDocument(this);
    chatHtml->setDefaultStyleSheet(cssString);
    setDocument(chatHtml);
    chatCursor = new QTextCursor(chatHtml);
    standardFormat.setLeftMargin(20);
    standardFormat.setTextIndent(-20);
    standardFormat.setTopMargin(3);
    indentedFormat.setLeftMargin(20);
    indentedFormat.setTextIndent(0);
    indentedFormat.setTopMargin(3);
    chatCursor->setBlockFormat(standardFormat);
}
